<script setup lang="ts">
  import {
    getCabinetType,
    getCrdaList,
    addCabinet,
    editCabinet,
  } from '@/api/archives';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import { watch } from 'vue';
  import { useUserStore } from '@/store';

  import { cloneDeep } from 'lodash-es';

  const props = defineProps({
    // 定义组件接收的 props  import { cloneDeep } from 'lodash-es';
    visible: Boolean,
    isEdit: Boolean,
    editParam: [Number, Object],
    title: String,
  });
  type OptionType = {
    value: string | number;
    label: string;
  };
  const formRef = ref<FormInstance | null>(null); //表单实例
  const userStore = useUserStore();
  const formFields = ref();
  const typeOptions = ref<OptionType[] | null>(null);
  const roomOptions = ref<OptionType[] | null>(null);
  const formData = reactive({
    cabinet_number: '', //档案柜编号 *
    cabinet_address: '', //档案柜地址 *
    cabinet_type_id: '', //档案柜类型id *
    cabinet_room_id: '', //所属档案室id *
    cabinet_user_id: '', //管理员id *
  });
  onMounted(() => {
    fetchTypeData();
    fetchRoomData();
  });
  //监听属性
  watch(
    () => props.editParam,
    (newVal) => {
      console.log('newVal', newVal);
      try {
        //清楚旧数据
        Object.keys(formData).forEach((key) => {
          formData[key] = '';
        });

        if (props.isEdit) {
          Object.assign(formData, cloneDeep(newVal));
        }
      } catch (error) {}
    },
    { immediate: true } //初始化时立即执行一次
  );

  formFields.value = [
    {
      label: '编号',
      name: 'cabinet_number',
      rules: [
        {
          required: true,
          message: '请输入编号',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
      fieldProps: {
        placeholder: '请输入编号',
        allowClear: true,
        maxLength: 200,
        span: 12,
      },
    },
    {
      name: 'cabinet_type_id',
      label: '类型',
      type: 'a-select',
      fieldProps: {
        placeholder: '请选择类型',
      },
      selectOptions: typeOptions,
    },
    {
      label: '位置',
      name: 'cabinet_address',
      fieldProps: {
        placeholder: '楼层-房间',
        allowClear: true,
        maxLength: 50,
      },
    },
    {
      label: '管理员',
      name: 'cabinet_user_id',
      type: 'a-select',
      fieldProps: {
        placeholder: '请选择管理员',
        span: 12,
        fieldNames: { value: 'user_id', label: 'user_name' },
        allowSearch: true,
      },
      selectOptions: userStore.allUserInfo,
    },
    {
      label: '所属档案室',
      name: 'cabinet_room_id',
      type: 'a-select',
      fieldProps: {
        span: 12,
        placeholder: '请选择所属档案室',
      },
      selectOptions: roomOptions,
    },
  ];
  //提交
  const handleSubmit = async () => {
    if (await formRef.value?.checkForm()) {
      Message.error('请正确填写表单！');
    } else {
      if (props.isEdit) {
        const {
          cabinet_number,
          cabinet_address,
          cabinet_type_id,
          cabinet_room_id,
          cabinet_user_id,
          cabinet_id,
        } = formRef.value?.formModel || {};

        // 组成新对象
        const newObject = {
          cabinet_number,
          cabinet_address,
          cabinet_type_id,
          cabinet_room_id,
          cabinet_user_id,
          cabinet_id,
        };
        editCabinet(newObject).then((res) => {
          if (res.code == 200) {
            Message.success(res?.msg);
            emit('update:visible', false);
            emit('refresh');
          }
        });
      } else {
        addCabinet({
          ...formRef.value?.formModel,
        }).then((res) => {
          if (res.code == 200) {
            Message.success(res?.msg);
            emit('update:visible', false);
            emit('refresh');
          }
        });
      }
    }
  };
  const emit = defineEmits(['update:visible', 'refresh']);
  const close = () => {
    emit('update:visible', false);
  };

  //下拉框的数据获取
  const fetchTypeData = async () => {
    const data = await getCabinetType(null);
    const filteredData = data.data.list.map((item: any) => ({
      label: item.type_name,
      value: item.type_id,
    }));
    typeOptions.value = filteredData;
  };
  const fetchRoomData = async () => {
    const data = await getCrdaList(null);
    const filteredData = data.data.list.map((item: any) => ({
      label: item.room_name,
      value: item.room_id,
    }));
    roomOptions.value = filteredData;
  };
</script>

<template>
  <a-modal
    :title="props.title"
    width="600px"
    :visible="visible"
    title-align="start"
    @Ok="handleSubmit"
    @cancel="close"
  >
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="formFields"
      :form-data="formData"
    ></pro-form>
  </a-modal>
</template>

<style scoped lang="less"></style>
